import 'package:flutter/material.dart';
import 'todo_page.dart';
import 'folder_page.dart';
import 'note_edit_page.dart';
import '../models/note.dart';
import '../service/database_service.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

class NoteSearchDelegate extends SearchDelegate<Note?> {
  final DatabaseService _databaseService;

  NoteSearchDelegate(this._databaseService);

  void _showPasswordInputDialog(BuildContext context, Function(String text) onPasswordEntered) {
    final TextEditingController passwordController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('请输入密码'),
        content: TextField(
          controller: passwordController,
          obscureText: true,
          decoration: const InputDecoration(hintText: '输入密码'),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context); 
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              String password = passwordController.text;
              if (password.isNotEmpty) {
                Navigator.pop(context); 
                onPasswordEntered(password);
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('密码不能为空')),
                );
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: const Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return FutureBuilder<List<Note>>(
      future: _databaseService.searchNotes(query),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.hasError) {
          return Center(child: Text('搜索出错: ${snapshot.error}'));
        }

        final notes = snapshot.data ?? [];
        
        if (notes.isEmpty) {
          return const Center(child: Text('未找到相关笔记'));
        }

        return ListView.builder(
          itemCount: notes.length,
          itemBuilder: (context, index) {
            final note = notes[index];
            return Card(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: ListTile(
                contentPadding: const EdgeInsets.only(left: 8, right: 16),
                horizontalTitleGap: 8,
                leading: note.isPinned
                    ? Icon(Icons.publish, color: Colors.blue.shade400)
                    : null,
                title: Text(
                  note.title.isEmpty ? '无标题' : note.title,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                subtitle: Text(
                  note.password?.isNotEmpty != true
                      ? note.content
                      : "******",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                trailing: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      '${note.updatedAt.month}/${note.updatedAt.day} ${note.updatedAt.hour}:${note.updatedAt.minute.toString().padLeft(2, '0')}',
                      style: const TextStyle(fontSize: 12),
                    ),
                    if( note.label?.isNotEmpty == true ) Container(
                      margin: const EdgeInsets.only(top: 4),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 4),
                      decoration: BoxDecoration(
                        color: Colors.blue.shade100,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        note.label ?? '',
                        style: const TextStyle(fontSize: 12),
                      ),
                    )
                  ],
                ),
                onTap: () async {
                  if (note.password?.isNotEmpty == true) {
                    _showPasswordInputDialog(context, (text) async {
                      if (note.password == text) {
                        await Navigator.push<Note>(
                          context,
                          MaterialPageRoute(
                            builder: (context) => NoteEditPage(note: note),
                          ),
                        );
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('密码错误')),
                        );
                      }
                    });
                  } else {
                    await Navigator.push<Note>(
                      context,
                      MaterialPageRoute(
                        builder: (context) => NoteEditPage(note: note),
                      ),
                    );
                  }
                },
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return buildResults(context);
  }
}

class NotePage extends StatefulWidget {
  const NotePage({super.key});

  @override
  State<NotePage> createState() => _NotePageState();
}

class _NotePageState extends State<NotePage> {
  int _currentIndex = 0; 

  final List<Widget> _pages = [
    const NoteListPage(), 
    const TodoPage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pages[_currentIndex], 
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.note),
            label: '笔记',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.check_circle_outline),
            label: '待办',
          ),
        ],
      ),
    );
  }
}

class NoteListPage extends StatefulWidget {
  const NoteListPage({super.key});

  @override
  State<NoteListPage> createState() => _NoteListPageState();
}

class _NoteListPageState extends State<NoteListPage> {
  final List<Note> _notes = []; 
  final DatabaseService _databaseService = DatabaseService(); 
  bool _isLoading = true; 

  @override
  void initState() {
    super.initState();
    _loadNotes();
  }

  Future<void> _loadNotes() async {
    try {
      final notes = await _databaseService.getAllNotes();
      setState(() {
        _notes.clear();
        _notes.addAll(notes);
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _showPasswordInputDialog(BuildContext context, Function(String text) onPasswordEntered) {
    final TextEditingController passwordController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('请输入密码'),
        content: TextField(
          controller: passwordController,
          obscureText: true,
          decoration: const InputDecoration(hintText: '输入密码'),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context); 
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              String password = passwordController.text;
              if (password.isNotEmpty) {
                Navigator.pop(context); 
                onPasswordEntered(password);
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('密码不能为空')),
                );
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _encryptionPasswordInputDialog(BuildContext context, Note note) {
    final TextEditingController passwordController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('请输入密码'),
        content: TextField(
          controller: passwordController,
          obscureText: true,
          decoration: const InputDecoration(hintText: '输入密码'),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context); 
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              String password = passwordController.text;
              if (password.isNotEmpty) {
                Navigator.pop(context); 
                await _databaseService.updateNote(note.copyWith(password: password));
                _loadNotes();
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('密码不能为空')),
                );
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 1,
        title: Row(
          children: [
            const Icon(Icons.article,size: 30),
            const SizedBox(width: 8,),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('全部笔记',style: TextStyle(fontWeight: FontWeight.bold),), 
                Text(
                  '${_notes.length}篇笔记', 
                  style: TextStyle(fontSize: 12, color: Colors.grey.shade700),
                ),
              ]
            ),
          ],
        ),
        leading: IconButton(
          icon: const Icon(Icons.menu),
          onPressed: () async {
            await Navigator.push<Note>(
              context,
              MaterialPageRoute(builder: (context) => const FolderPage()),
            );
            _loadNotes();
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              showSearch(
                context: context,
                delegate: NoteSearchDelegate(_databaseService),
              );
            },
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _notes.isEmpty
              ? const Center(child: Text('暂无笔记，点击右下角创建'))
              : ListView.builder(
                  itemCount: _notes.length,
                  itemBuilder: (context, index) {
                    final note = _notes[index];
                    return Slidable(
                      key: Key(note.id),
                      endActionPane: ActionPane(
                        motion: const ScrollMotion(),
                        children: [
                          TextButton(
                            onPressed: () async {
                              try {
                                await _databaseService.updateNote(note.copyWith(isPinned: !note.isPinned));
                                _loadNotes();
                                Slidable.of(context)?.close();
                              } catch (e) {
                                if (mounted) {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(content: Text('置顶笔记失败: $e')),
                                  );
                                }
                              }
                            },
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  padding: const EdgeInsets.all(8.0), 
                                  decoration: BoxDecoration(
                                    color: Colors.grey.shade400, 
                                    shape: BoxShape.circle, 
                                  ),
                                  child: const Icon(Icons.arrow_upward, color: Colors.black,),
                                ),
                                const SizedBox(height: 4), 
                                Text(note.isPinned ? '取消置顶' : '置顶', style: const TextStyle(fontSize: 12, color: Colors.black), 
                                ),
                              ],
                            ),
                          ),
                          TextButton(
                            onPressed: () async {
                              await Slidable.of(context)?.close();
                              _encryptionPasswordInputDialog(context, note); 
                            },
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  padding: const EdgeInsets.all(8.0), 
                                  decoration: BoxDecoration(
                                    color: Colors.grey.shade400, 
                                    shape: BoxShape.circle, 
                                  ),
                                  child: const Icon(Icons.lock, color: Colors.black,),
                                ),
                                const SizedBox(height: 4), 
                                const Text('加密', style: TextStyle(fontSize: 12, color: Colors.black), 
                                ),
                              ],
                            ),
                          ),
                          TextButton(
                            onPressed: () async {
                              final shouldDelete =
                                  await _showDeleteDialog(note);
                              if (shouldDelete) {
                                try {
                                  await _databaseService.deleteNote(note.id);
                                  _loadNotes();
                                } catch (e) {
                                  if (mounted) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(content: Text('删除笔记失败: $e')),
                                    );
                                  }
                                }
                              }
                            },
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  padding: const EdgeInsets.all(8.0), 
                                  decoration: BoxDecoration(
                                    color: Colors.grey.shade400, 
                                    shape: BoxShape.circle, 
                                  ),
                                  child: const Icon(Icons.delete, color: Colors.black,),
                                ),
                                const SizedBox(height: 4), 
                                const Text('删除', style: TextStyle(fontSize: 12, color: Colors.black), 
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      child: Card(
                        margin: const EdgeInsets.symmetric(
                            horizontal: 16, vertical: 8),
                        child: ListTile(
                          horizontalTitleGap: 8,
                          leading: note.isPinned
                              ? Icon(Icons.publish, color: Colors.blue.shade400,)
                              : null,
                          title: Text(
                            note.title.isEmpty ? '无标题' : note.title,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          subtitle: Text(
                            note.password?.isNotEmpty != true
                                ? note.content
                                : "******",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          trailing: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Text(
                                '${note.updatedAt.month}/${note.updatedAt.day} ${note.updatedAt.hour}:${note.updatedAt.minute.toString().padLeft(2, '0')}',
                                style: const TextStyle(fontSize: 12),
                              ),
                              if( note.label?.isNotEmpty == true ) Container(
                                margin: const EdgeInsets.only(top: 4),
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 12, vertical: 4),
                                decoration: BoxDecoration(
                                  color: Colors.blue.shade100,
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                child: Text(
                                  note.label ?? '',
                                  style: const TextStyle(fontSize: 12),
                                ),
                              ) 
                            ],
                          ),
                          onTap: () {
                            if (note.password?.isNotEmpty == true) {
                              _showPasswordInputDialog(context, (text) {
                                if (note.password == text) {
                                  _editNote(note);
                                } else {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('密码错误')),
                                  );
                                }
                              });
                            } else {
                              _editNote(note);
                            }
                          },
                        ),
                      ),
                    );
                  },
                ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _createNote(),
        child: const Icon(Icons.add),
      ),
    );
  }

  Future<void> _createNote() async {
    final note = await Navigator.push<Note>(
      context,
      MaterialPageRoute(
        builder: (context) => const NoteEditPage()
      ),
    );
    if (note != null) {
      _loadNotes();
    }
  }

  Future<void> _editNote(Note note) async {
    final updatedNote = await Navigator.push<Note>(
      context,
      MaterialPageRoute(
        builder: (context) => NoteEditPage(note: note),
      ),
    );
    if (updatedNote != null) {
      _loadNotes();
    }
  }

  Future<bool> _showDeleteDialog(Note note) async {
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除笔记'),
        content: const Text('确定删除此笔记吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('删除'),
          ),
        ],
      ),
    );
    return result ?? false;
  }
}
